import React, { Component } from 'react'
import './index.css'
import PubSub from 'pubsub-js'

export default class List extends Component {
    // 初始化状态
    // 初始化状态
    state = {
        users: [], // users初始化为数组
        isFirst: true, // 是否为第一次打开页面
        isLoading: false, // 标识是否处于加载中
        err: '', // 存储请求相关错误信息
    }

    componentDidMount() {
        // 订阅消息
        this.event = PubSub.subscribe('search', (msg, stateObj) => {
            this.setState(stateObj)
        })
    }

    componentWillUnmount() {
        // 取消订阅
        PubSub.unsubscribe(this.event)
    }


    render() {
        // 应该从state中解构而不是props
        const { users, isFirst, isLoading, err } = this.state;
        return (
            <div>
                {
                    isFirst ? <h2>欢迎使用，输入关键字，点击搜索</h2> :
                        isLoading ? <h2>Loading...</h2> :
                            err ? <h2 style={{ color: 'red' }}>{err}</h2> :
                                users.map((userObj) => {
                                    return (
                                        // 渲染数据块
                                        <div key={userObj.id} className="card">
                                            <a rel="noreferrer" href={userObj.html_url} target="_blank">
                                                <img alt="avatar" src={userObj.avatar_url} style={{ width: '100px' }} />
                                            </a>
                                            <p className="card-text">{userObj.login}</p>
                                        </div>
                                    )
                                })
                }
            </div>
        )
    }
}
